package com.scalar.forecast.forecastEntry.actionCommands;

import com.scalar.forecast.actionCommands.ActionCommand;
import com.scalar.forecast.forecastEntry.forms.ForecastEntrySearchForm;
import com.scalar.forecast.forecastEntry.dao.ForecastEntrySearchDAO;
import com.scalar.forecast.forecastEntry.SearchFieldListComparator;
import com.scalar.forecast.forecastEntry.SearchField;
import com.scalar.forecast.forecastSetup.ForecastTimeFrame;
import com.scalar.forecast.forecastSetup.ForecastEntryField;
import com.scalar.forecast.forecastSetup.dao.ForecastSetupDAO;
import com.scalar.forecast.commons.SessionKeys;
import com.scalar.chiptrack.sales.dao.CustomerRelationshipDAO;
import com.scalar.forecast.commons.Labels;
import com.scalar.forecast.commons.Constants;
import com.scalar.ScalarException;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.util.LabelValueBean;
import org.apache.struts.util.MessageResources;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

/**
 * User: Sujan Kumar
 * Date: Feb 11, 2005
 * Time: 11:56:28 AM
 */
public class ForecastEntrySearchNewCommand extends ActionCommand
{
    public ActionForward execute ( ActionMapping mapping,
                                            ActionForm form,
                                            HttpServletRequest request,
                                            HttpServletResponse response )
    {
        ForecastEntrySearchForm forecastEntrySearchForm = ( ForecastEntrySearchForm ) form;
        if ( forecastEntrySearchForm == null )
        {
            forecastEntrySearchForm = new ForecastEntrySearchForm();
        }
        HashMap errors = new HashMap ();
        Calendar  now = Calendar.getInstance();
        ArrayList searchFieldList = new ArrayList();
        ArrayList forecastSetupFields = null;
		boolean isOrderBySet = false;
        try
        {
            forecastSetupFields = ForecastSetupDAO.getForecastSetupFields(null);
			if ( forecastEntrySearchForm.getOrderBy ( ) == null || forecastEntrySearchForm.getOrderBy ().trim().length() == 0 )
			{
				isOrderBySet = true;
            	forecastEntrySearchForm.setOrderBy( getDefaultOrderBy ( forecastSetupFields ) );
				forecastEntrySearchForm.setShowActualValues( false );
        		forecastEntrySearchForm.setShowAllSalesPersonsActualValues( false );
				forecastEntrySearchForm.setYear( now.get ( Calendar.YEAR ) );
			}
            request.setAttribute ( "forecastSetupFields", forecastSetupFields );
        }
        catch ( ScalarException e )
        {
            errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_COULD_NOT_LOAD_FORECAST_SETUP_FIELDS );
            request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
            System.out.println ( "----------exception in search new Command:" );
            e.printStackTrace();
            return mapping.findForward ( "errorPage" );
        }
        try
        {
            searchFieldList = ForecastEntrySearchDAO.getForecastSetupSearchFields(null);
            loadSearchFieldListPropertyValues(forecastEntrySearchForm,searchFieldList);
        }
        catch ( Exception e )
        {
            errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_COULD_NOT_LOAD_SEARCH_FIELDS );
            request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
            System.out.println ( "----------exception in search new Command:" );
            e.printStackTrace();
            return mapping.findForward ( "errorPage" );
        }
        setSortOrder ( forecastEntrySearchForm.getOrderBy(), searchFieldList );
        Collections.sort( searchFieldList, new SearchFieldListComparator() );
        forecastEntrySearchForm.setSearchFieldList( searchFieldList );

        try
        {
            ForecastTimeFrame timeframe = ForecastSetupDAO.getForecastTimeFrame(null);
            //this request field is used to display the label after the showNext textfield.
            if ( "Month".equalsIgnoreCase( timeframe.getTfName() ) )
            {
				if ( isOrderBySet )
				{
                	forecastEntrySearchForm.setStartMonth_Quarter_Year( now.get( Calendar.MONTH ) );
                	forecastEntrySearchForm.setShowNext(6);
				}
                request.setAttribute ( "showNext", "Months" );
            }
            else if ( "Quarter".equalsIgnoreCase( timeframe.getTfName() ) )
            {
                int currentQuarter = -1;
                try
                {
                    currentQuarter = ForecastEntrySearchDAO.getCurrentQuarter(null);
                }
                catch ( Exception e)
                {
                    System.out.println ( "--Exception in getting the current Quarter---" );
                    e.printStackTrace();
                }
				if ( isOrderBySet )
				{
					forecastEntrySearchForm.setStartMonth_Quarter_Year( currentQuarter );
					forecastEntrySearchForm.setShowNext(4);
				}
                request.setAttribute ( "showNext", "Quarters" );
            }
            else if ( "Year".equalsIgnoreCase( timeframe.getTfName() ) )
            {
				if ( isOrderBySet )
				{
					forecastEntrySearchForm.setStartMonth_Quarter_Year( now.get( Calendar.YEAR ) );
					forecastEntrySearchForm.setShowNext(3);
				}
                request.setAttribute ( "showNext", "Years" );
            }
        }
        catch ( Exception e )
        {
            errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_COULD_NOT_LOAD_FORECAST_TIMEFRAME );
            request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
            System.out.println ( "----------exception while getting the timeframe-----");
            e.printStackTrace();
            return mapping.findForward ( "errorPage" );
        }
        ActionForward actionForward = mapping.findForward ( "searchPage" );
        return actionForward;
    }

    /**
     * This method loads the forecast setup list values to be displayed in each search field.
     * @param searchFieldList
     *ArrayList containig the searchFields
     */
    public static void loadSearchFieldListPropertyValues( ForecastEntrySearchForm forecastEntrySearchForm,ArrayList searchFieldList )
    {
        boolean isByCustomer = false;
        boolean isByProject = false;
        boolean isByProduct = false;
        boolean isByOdm     = false;
        SearchField searchField = null;
        int listSize = searchFieldList.size();
        for ( int i=0; i < listSize; i++ )
        {
            searchField = ( SearchField )searchFieldList.get ( i );
            if ( "By Customer".equalsIgnoreCase( searchField.getName() ) )
            {
                isByCustomer = searchField.isDisplay();
            }
            else if ( "By Project".equalsIgnoreCase( searchField.getName() ) )
            {
                isByProject = searchField.isDisplay();
            }
            else if ( "By Product".equalsIgnoreCase( searchField.getName() ) )
            {
                isByProduct = searchField.isDisplay();
            }
            else if ( "By ODM".equalsIgnoreCase( searchField.getName() ) )
            {
                isByOdm = searchField.isDisplay();
            }
        }
        LabelValueBean labelValueBean = null;
        for ( int i=0; i < listSize; i++ )
        {
            searchField = ( SearchField )searchFieldList.get ( i );
            if ( "By Customer".equalsIgnoreCase( searchField.getName() ) )
            {
                ArrayList customersList = new ArrayList ();
                if ( isByCustomer )
                {
                    try
                    {
                        if ( Constants.FORECAST_SETUP_BY_CUSTOMER.equalsIgnoreCase( forecastEntrySearchForm.getOrderBy() ) )
                        {
                            customersList = ForecastEntrySearchDAO.getAllCustomers(null);
                        }
                        else if ( Constants.FORECAST_SETUP_BY_PRODUCT.equalsIgnoreCase( forecastEntrySearchForm.getOrderBy() ) )
                        {
                            if ( isByProject )
                            {
                                customersList = ForecastEntrySearchDAO.getAllCustomersForProject ( null, forecastEntrySearchForm.getProjectId() );
                            }
                            else
                            {
                                customersList = ForecastEntrySearchDAO.getAllCustomers(null);
                            }
                        }
                        else if ( Constants.FORECAST_SETUP_BY_PROJECT.equalsIgnoreCase( forecastEntrySearchForm.getOrderBy() ) )
                        {
                            customersList = ForecastEntrySearchDAO.getAllCustomersForProject ( null, forecastEntrySearchForm.getProjectId() );
                        }
                    }
                    catch ( Exception e)
                    {
                        System.out.println ( "---Exception while getting Customers List----");
                        e.printStackTrace();
                    }
                }
                labelValueBean = new LabelValueBean( "---Select Customer---", "-1" );
                customersList.add ( 0, labelValueBean );
                searchField.setPropertyValues ( customersList );
            }
            else if ( "By Project".equalsIgnoreCase( searchField.getName() ) )
            {
                ArrayList  projects = new ArrayList();
                if ( isByProject )
                {
                    try
                    {
                        if ( Constants.FORECAST_SETUP_BY_CUSTOMER.equalsIgnoreCase( forecastEntrySearchForm.getOrderBy() ) )
                        {
                            projects = ForecastEntrySearchDAO.getAllProjectsForCustomer(null, forecastEntrySearchForm.getCustId() );
                        }
                        else if ( Constants.FORECAST_SETUP_BY_PRODUCT.equalsIgnoreCase( forecastEntrySearchForm.getOrderBy() ) )
                        {
                            projects = ForecastEntrySearchDAO.getAllProjectsForProduct ( null, forecastEntrySearchForm.getProductId() );
                        }
                        else if ( Constants.FORECAST_SETUP_BY_PROJECT.equalsIgnoreCase( forecastEntrySearchForm.getOrderBy() ) )
                        {
                            projects = ForecastEntrySearchDAO.getAllProjects(null);
                        }

                    }
                    catch ( Exception e)
                    {
                        System.out.println ( "---Exception while getting Customers List----");
                        e.printStackTrace();
                    }
                }
                //-------------------
                /*if ( isByCustomer ) // if the customer is selected then load projects related to the customer
                {
                    try
                    {
                        projects = ForecastEntrySearchDAO.getAllProjectsForCustomer(null, forecastEntrySearchForm.getCustId() );
                    }
                    catch ( Exception e )
                    {
                        System.out.println ( "---Exception While loading the projects w.r.t Cusotmer---" );
                        e.printStackTrace();
                    }
                }
                else
                {
                    try
                    {
                        projects = ForecastEntrySearchDAO.getAllProjects(null);
                    }
                    catch ( Exception e )
                    {
                        System.out.println ( "---Exception While loading all projects ---" );
                        e.printStackTrace();
                    }
                }*/
                labelValueBean = new LabelValueBean( "---Select Project---", "-1" );
                projects.add ( 0, labelValueBean );
                searchField.setPropertyValues ( projects );
            }
            else if ( "By Product".equalsIgnoreCase( searchField.getName() ) )
            {
                ArrayList products = new ArrayList();

                if ( isByProduct )
                {
                    try
                    {
                        if ( Constants.FORECAST_SETUP_BY_CUSTOMER.equalsIgnoreCase( forecastEntrySearchForm.getOrderBy() ) )
                        {
                            if ( isByProject )
                            {
                                products = ForecastEntrySearchDAO.getAllProductsForProject ( null, forecastEntrySearchForm.getProjectId() );
                            }
                            else
                            {
                                products = ForecastEntrySearchDAO.getAllProducts(null);
                            }
                        }
                        else if ( Constants.FORECAST_SETUP_BY_PRODUCT.equalsIgnoreCase( forecastEntrySearchForm.getOrderBy() ) )
                        {
                            products = ForecastEntrySearchDAO.getAllProducts(null);
                        }
                        else if ( Constants.FORECAST_SETUP_BY_PROJECT.equalsIgnoreCase( forecastEntrySearchForm.getOrderBy() ) )
                        {
                            products = ForecastEntrySearchDAO.getAllProductsForProject(null, forecastEntrySearchForm.getProjectId() );
                        }
                    }
                    catch ( Exception e)
                    {
                        System.out.println ( "---Exception while getting Customers List----");
                        e.printStackTrace();
                    }
                }
                /*if ( isByProject )
                {
                    try
                    {
                        products = ForecastEntrySearchDAO.getAllProductsForProject(null, forecastEntrySearchForm.getProjectId() );
                    }
                    catch ( Exception e )
                    {
                        System.out.println ( "---Exception while getting products related to projects----" );
                        e.printStackTrace();
                    }
                }
                else
                {
                    try
                    {
                        products = ForecastEntrySearchDAO.getAllProducts(null);
                    }
                    catch ( Exception e )
                    {
                        System.out.println ( "--Exception while loading all the products---");
                        e.printStackTrace();
                    }
                }*/
                labelValueBean = new LabelValueBean( "---Select Product---", "-1" );
                products.add ( 0, labelValueBean );
                searchField.setPropertyValues( products );
            }
            else if ( "By ODM".equalsIgnoreCase( searchField.getName() ) )
            {
                ArrayList odmList = new ArrayList();

                if ( isByCustomer )
                {
                    try
                    {
                        odmList = CustomerRelationshipDAO.getAllOdmsForCustomer( forecastEntrySearchForm.getCustId() + "" );
                    }
                    catch ( Exception e )
                    {
                        System.out.println ( "---Exception while loading ODMs----" );
                        e.printStackTrace();
                    }
                }
                else
                {
                    //todo check..
                    //no need to load odms since odm's should be displayed if customer is selected.
                }
                String odmLabel = MessageResources.getMessageResources( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage("label.sales.endCustomer");
                labelValueBean = new LabelValueBean( "---Select "+odmLabel+"---", "-1" );
                odmList.add ( 0, labelValueBean );
                searchField.setPropertyValues( odmList );
            }
        }
    }
    public static String getDefaultOrderBy ( ArrayList forecastSetupFields )
    {
        int forecastSetupFieldsSize = forecastSetupFields.size();
        ForecastEntryField forecastEntryField = null;
        String defaultOrderBy = Constants.FORECAST_SETUP_BY_PRODUCT;
        for ( int i = 0; i < forecastSetupFieldsSize; i++ )
        {
            forecastEntryField = ( ForecastEntryField )forecastSetupFields.get( i );
            if ( Constants.FORECAST_SETUP_BY_CUSTOMER.equalsIgnoreCase( forecastEntryField.getEntryName() ) && forecastEntryField.isEntrySelected() )
            {
                defaultOrderBy = forecastEntryField.getEntryName();
            }
        }
        return defaultOrderBy;
    }
    public static void setSortOrder ( String orderBy, ArrayList searchFieldList )
    {
        int searchFieldListSize = searchFieldList.size();
        SearchField searchField = null;
        for ( int i = 0; i < searchFieldListSize; i++ )
        {
            searchField = ( SearchField )searchFieldList.get ( i );
            if ( Constants.FORECAST_SETUP_BY_CUSTOMER.equalsIgnoreCase( searchField.getName() ) )
            {
                if ( Constants.FORECAST_SETUP_BY_CUSTOMER.equalsIgnoreCase( orderBy ) )
                {
                    searchField.setSortOrder( 1 );
                }
                else if ( Constants.FORECAST_SETUP_BY_PRODUCT.equalsIgnoreCase( orderBy ) )
                {
                    searchField.setSortOrder( 3 );
                }
                else if ( Constants.FORECAST_SETUP_BY_PROJECT.equalsIgnoreCase( orderBy ) )
                {
                    searchField.setSortOrder( 3 );
                }
            }
            else if ( Constants.FORECAST_SETUP_BY_PRODUCT.equalsIgnoreCase( searchField.getName() ) )
            {
                if ( Constants.FORECAST_SETUP_BY_CUSTOMER.equalsIgnoreCase( orderBy ) )
                {
                    searchField.setSortOrder( 3 );
                }
                else if ( Constants.FORECAST_SETUP_BY_PRODUCT.equalsIgnoreCase( orderBy ) )
                {
                    searchField.setSortOrder( 1 );
                }
                else if ( Constants.FORECAST_SETUP_BY_PROJECT.equalsIgnoreCase( orderBy ) )
                {
                    searchField.setSortOrder( 2 );
                }
            }
            else if ( Constants.FORECAST_SETUP_BY_PROJECT.equalsIgnoreCase( searchField.getName() ) )
            {
                if ( Constants.FORECAST_SETUP_BY_CUSTOMER.equalsIgnoreCase( orderBy ) )
                {
                    searchField.setSortOrder( 2 );
                }
                else if ( Constants.FORECAST_SETUP_BY_PRODUCT.equalsIgnoreCase( orderBy ) )
                {
                    searchField.setSortOrder( 2 );
                }
                else if ( Constants.FORECAST_SETUP_BY_PROJECT.equalsIgnoreCase( orderBy ) )
                {
                    searchField.setSortOrder( 1 );
                }
            }
        }
    }
}
